﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.classfile
{
    class ClassReader
    {
        private byte[] data;
        private int readerIndex = 0;

        public ClassReader(byte[] data)
        {
            this.data = data;
            readerIndex = 0;
        }
        public byte ReadByte()
        {
            return data[readerIndex++];
        }

        public byte[] ReadBytes(uint length)
        {
            byte[] result = new byte[length];
            for (uint i = 0; i < length; i++)
            {
                result[i] = ReadByte();
            }
            return result;
        }

        public uint ReadUint()
        {
            byte[] temp = ReadBytes(4);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(temp);
            return BitConverter.ToUInt32(temp, 0);
        }

        public int ReadInt()
        {
            byte[] temp = ReadBytes(4);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(temp);
            return BitConverter.ToInt32(temp, 0);
        }

        public ushort ReadUshort()
        {
            byte[] temp = ReadBytes(2);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(temp);
            return BitConverter.ToUInt16(temp, 0);
        }

        public ulong ReadUlong()
        {
            byte[] temp = ReadBytes(8);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(temp);
            return BitConverter.ToUInt64(temp, 0);
        }

        public long ReadLong()
        {
            byte[] temp = ReadBytes(8);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(temp);
            return BitConverter.ToInt64(temp, 0);
        }

        public float ReadFloat()
        {
            byte[] temp = ReadBytes(4);
            Array.Reverse(temp);
            return BitConverter.ToSingle(temp, 0);
        }

        public double ReadDouble()
        {
            byte[] temp = ReadBytes(8);
            Array.Reverse(temp);
            return BitConverter.ToDouble(temp, 0);
        }

        public string ReadString()
        {
            ushort len = ReadUshort();
            byte[] buffer = ReadBytes(len);
            return Encoding.UTF8.GetString(buffer);
        }
    }
}
